// 公告管理模块

var express = require('express');
const { getAll, getOne, exec } = require('../db');
const { debug } = require('../config');
var router = express.Router();
// 前台获取所有公告
router.get('/font', async function (req, res, next) {
  let { page = 1, size = 4 } = req.query;
  let offset = (page - 1) * size;
  let sql = `select count(*) as total from notice  `;
  const obj = await getOne(sql); //total
  sql = `select notice_time, notice_content,notice_addr,notice_radius,notice_cate
  from notice limit ${offset},${size}`;

  sql = `select notice_time, notice_content,notice_addr,notice_radius,notice_cate
  from notice order by notice_time desc limit ${offset},${size}`;
  try {
    const data = await getAll(sql);
    res.send({
      code: 0,
      message: '获取所有公告成功',
      total: obj.total,
      result: data,
    });
  } catch (err) {
    res.send({
      code: 500,
      message: '获取所有公告失败',
      result: debug ? '' : err,
    });
  }
});
// 中台获取所有公告
router.get('/middle', async function (req, res, next) {
  let { page = 1, size = 4 } = req.query;
  let offset = (page - 1) * size;
  let sql = `select *
  from notice limit ${offset},${size}`;
  try {
    const data = await getAll(sql);
    res.send({
      code: 0,
      message: '获取所有公告成功',
      result: data,
    });
  } catch (err) {
    res.send({
      code: 500,
      message: '获取所有公告失败',
      result: debug ? '' : err,
    });
  }
});
// 获取公告总数
router.get('/total', async function (req, res) {
  let sql = `select count(*) as total from notice`;
  try {
    const data = await getOne(sql);
    res.send({
      code: 0,
      message: '获取总数成功',
      result: data,
    });
  } catch (err) {
    res.send({
      code: 500,
      message: '获取总数失败',
      result: debug ? '' : err,
    });
  }
});

//发布公告
router.post('/', async function (req, res) {
  let { cate, addr, content, uid, radius, fid } = req.body;
  let sql = `insert into 
  notice(notice_uid,notice_cate,notice_addr,notice_content,notice_radius) 
  values('${uid}','${cate}','${addr}','${content}','${radius}')`;
  console.log(sql);
  try {
    const data = await exec(sql);
    console.log(data);
    res.send({
      code: 0,
      message: '发布公告成功',
      result: {
        id: data.insertId,
      },
    });
  } catch (err) {
    res.send({
      code: 500,
      message: '发布公告失败',
      result: debug ? '' : err,
    });
  }
});
// 删除公告
router.delete('/:id', async function (req, res) {
  let { id } = req.params;
  let sql = `delete from notice where notice_id = ${id}`;
  try {
    const data = await exec(sql);
    res.send({
      code: 0,
      message: '删除用户成功',
      result: '',
    });
  } catch (err) {
    res.send({
      code: 500,
      message: '删除失败',
      result: debug ? '' : err,
    });
  }
});

module.exports = router;
